package com.hxh.crud.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxh.crud.bean.Department;
import com.hxh.crud.bean.DepartmentExample;
import com.hxh.crud.bean.Employee;
import com.hxh.crud.bean.EmployeeExample;
import com.hxh.crud.dao.DepartmentMapper;
import com.hxh.crud.dao.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @CreatedBy: hxh
 * @Date: 2020/2/28 14:04
 * @Description: 部门逻辑层
 * @TODO: 加油吧！骚年！
 */
@Service
public class DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    public PageInfo<Department> getDepts(int pageNum, int pageSize) {
        DepartmentExample departmentExample = new DepartmentExample();
        DepartmentExample.Criteria criteria = departmentExample.createCriteria();
        criteria.andDeptStatusEqualTo(1);
        PageHelper.startPage(pageNum, pageSize);
        List<Department> departmentList = departmentMapper.selectByExample(departmentExample);
        return new PageInfo<>(departmentList);
    }

    public boolean checkDept(String deptName, String deptId) {
        DepartmentExample departmentExample = new DepartmentExample();
        DepartmentExample.Criteria criteria = departmentExample.createCriteria();
        criteria.andDeptStatusEqualTo(1);
        criteria.andDeptNameEqualTo(deptName);
        if (deptId != null) {
            criteria.andDeptIdNotEqualTo(deptId);
        }
        long l = departmentMapper.countByExample(departmentExample);
        return l != 0;
    }

    public void addDept(String deptName) {
        Department department = new Department(UUID.randomUUID().toString(), deptName, 1);
        departmentMapper.insertSelective(department);
    }

    public void editDept(String deptName, String deptId) {
        Department department = new Department(deptId, deptName, 1);
        departmentMapper.updateByPrimaryKeySelective(department);
    }

    public void delDept(List<Department> departmentList) {
        for (Department department : departmentList) {
            EmployeeExample employeeExample = new EmployeeExample();
            EmployeeExample.Criteria criteria = employeeExample.createCriteria();
            criteria.andDIdEqualTo(department.getDeptId());
            criteria.andEmpStatusEqualTo(1);
            List<Employee> employeeList = employeeMapper.selectByExampleWithDept(employeeExample);
            for (Employee employee : employeeList) {
                employee.setEmpStatus(0);
                employeeMapper.updateByPrimaryKeySelective(employee);
            }
            department.setDeptStatus(0);
            departmentMapper.updateByPrimaryKeySelective(department);
        }
    }

}
